<template>
  <Form
    ref="formRef"
    layout="inline"
    name="dynamic_form_nest_item"
    :model="dynamicValidateForm"
    :label-col="{ style: { width: '80px' } }"
    @finishFailed="onSubmit"
    :colon="false"
    autocomplete="off"
  >
    <div class="md:flex flex-wrap">
      <Space
        v-for="(container, index) in dynamicValidateForm"
        :key="index"
        style="display: flex; margin-bottom: 8px"
        align="baseline"
      >
        <FormItem
          :name="[index, 'nameSpace']"
          label="命名空间:"
          :labelCol="{ span: 12 }"
          :rules="{
            required: true,
            message: '请选择命名空间',
          }"
        >
          <Select
            @select="handleSelect"
            v-model:value="container.nameSpace"
            :options="nameSpaceList.map((a) => ({ value: a.value, label: a.value, key: index, disabled: a.disabled }))"
            style="width: 170px"
          ></Select>
        </FormItem>
        <FormItem
          label="工作负载:"
          :name="[index, 'appName']"
          :rules="{
            required: true,
            message: '请选择工作负载',
          }"
        >
          <Select
            mode="multiple"
            v-model:value="container.appName"
            :options="(container.appNameList || []).map((a) => ({ value: a, label: a }))"
            style="width: 170px"
          ></Select>
        </FormItem>
        <MinusCircleOutlined
          v-if="dynamicValidateForm.length > 1"
          style="color: #ff0071"
          class="dynamic-delete-button ml-3px"
          :disabled="dynamicValidateForm.length === 1"
          @click="remove(index)"
        />
        <PlusCircleOutlined style="color: #3361e8" @click="addSight" v-if="index === dynamicValidateForm.length - 1" />
      </Space>
    </div>
  </Form>
</template>
<script lang="ts" setup>
/* eslint-disable*/
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons-vue';
import type { Ref } from 'vue';
import { onMounted, ref } from 'vue';
import { Form, FormItem, Select, Space } from 'ant-design-vue';
import {
  getDeploymentList,
  getNamespaceList,
} from '/@/api/maintenance-center/resource-monitor/for-platform/resourceMonitor';

interface Containers {
  nameSpace: string;
  appName: string[];
  appNameList: string[];
}

interface NameSpace {
  value: string;
  disabled: boolean;
}

const emit = defineEmits(['getRef']);

let nameSpaceList = ref<NameSpace[]>([]);
let tempList = [];
const formRef = ref();

function getNameSpaceList() {
  getNamespaceList().then((res: string[]) => {
    res.forEach((a) => {
      nameSpaceList.value.push({ value: a, disabled: false });
    });
  });
}

onMounted(() => {
  getNameSpaceList();
});

const dynamicValidateForm: Ref<Containers[]> = ref([
  {
    nameSpace: '',
    appName: [],
    appNameList: [],
  },
]);

function findNameSpace(subNamespace) {
  const nameSpace = nameSpaceList.value.filter((e) => e.value === subNamespace)[0];
  return nameSpace;
}

const remove = (item) => {
  let nameSpace = findNameSpace(dynamicValidateForm.value[item].nameSpace);
  if (nameSpace) nameSpace.disabled = false;
  dynamicValidateForm.value.splice(item, 1);
};
const addSight = () => {
  dynamicValidateForm.value.push({
    nameSpace: '',
    appName: [],
    appNameList: [],
  });
};
const onSubmit = async () => {
  return formRef.value.validate();
};

async function handleSelect(subNameSpace, other) {
  tempList.push(subNameSpace);

  let nameSpace = findNameSpace(subNameSpace);
  nameSpace.disabled = true;

  tempList.forEach((item) => {
    let flag = false;
    dynamicValidateForm.value.forEach((temp) => {
      if (temp.nameSpace === item) {
        flag = true;
      }
    });
    if (flag === false) {
      let nameSpace = findNameSpace(item);
      nameSpace.disabled = false;
      tempList.pop(item);
      dynamicValidateForm.value.forEach((temp) => {
        if (temp.nameSpace === subNameSpace) {
          temp.appName = [];
          temp.appNameList = getDeploymentList({ nameSpace: subNameSpace });
        }
      });
    }
  });

  let appNameList: any[] = [];
  appNameList = await getDeploymentList({ nameSpace: subNameSpace });
  dynamicValidateForm.value[other.key]['appNameList'] = appNameList;
  return appNameList;
}

const resetForm = () => {
  tempList = [];
  nameSpaceList.value.forEach((item) => {
    item.disabled = false;
  });
  dynamicValidateForm.value = [
    {
      nameSpace: '',
      appName: [],
      appNameList: [],
    },
  ];
};

defineExpose({ resetForm, onSubmit });
</script>
